package com.edu.gateway.base;


import com.alibaba.fastjson.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class GatewayHelper {

    public static Mono<Void> ok(ServerWebExchange exchange){
        return resp(exchange,HttpStatus.OK,R.ok());
    }

    public static Mono<Void> ok(ServerWebExchange exchange, String data){
        return resp(exchange,HttpStatus.OK,R.ok(data));
    }

    public static Mono<Void> fail(ServerWebExchange exchange, String data){
        return resp(exchange,HttpStatus.INTERNAL_SERVER_ERROR,R.fail(data));
    }

    public static Mono<Void> fail(ServerWebExchange exchange, GateWayResultCode code){
        return resp(exchange,HttpStatus.INTERNAL_SERVER_ERROR,R.fail(code.getMsg()).setCode(code.getCode()));
    }

    public static Mono<Void> noAuth(ServerWebExchange exchange){
        return resp(exchange,HttpStatus.UNAUTHORIZED,R.ok("no auth"));
    }

    public static Mono<Void> resp(ServerWebExchange exchange,HttpStatus status,R r){
        exchange.getResponse().setStatusCode(status);
        exchange.getResponse().getHeaders().add("Content-Type","application/json;charset=UTF-8");
        DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(JSON.toJSONString(r).getBytes(StandardCharsets.UTF_8));
        return exchange.getResponse().writeWith(Mono.just(wrap));
    }
}
